package org.jeecgframework.web.util;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.jeecgframework.web.system.pojo.base.ZyFileLogEntity;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;



/**
* @ClassName: UploadFileUtil 
* @Description: 文件相关处理 
* @author dongzq 
* @date 2015年4月30日 下午3:56:37 
*
 */
public class UploadFileUtil {

    private static final String DEFAULTIMGPATH = "\\webpage\\com\\wx\\wx-plug-in\\images\\cfff.jpg";

	
	/**
	 * @author dzq
	 * 2016-4-14 上午11:04:59
	 * Description 文件上传入口 
	 * @param request request
	 * @return
	 */
	public static FileBean UploadFile(HttpServletRequest request) { // NOPMD by dzqThinkpad on 16-4-1 下午4:33
		MultipartHttpServletRequest req = (MultipartHttpServletRequest) request;
		MultipartFile multipartFile = req.getFile("Filedata");
		String suffix = multipartFile.getOriginalFilename().substring  
				(multipartFile.getOriginalFilename().lastIndexOf("."));     
		///**使用UUID生成文件名称**/    
//		String filePath = StaticValue.UPLOAD_PATH + "documents/";
		String filePath = StaticValue.UPLOAD_PATH;
//		String baseDirPath = req.getSession().getServletContext().getRealPath("/");
//		File fileDirectory = new File(baseDirPath + filePath);
		File fileDirectory = new File(filePath);
		if  (!fileDirectory.exists()  && !fileDirectory.isDirectory()){
			fileDirectory.mkdirs();
		}
		String newFileName = UUID.randomUUID().toString().replace("-", "")+ suffix;//构建文件名称     
		String fileRealName = multipartFile.getOriginalFilename();
		String uploadPath = filePath + newFileName;
//		File file = new File(baseDirPath + "/"+ uploadPath);
		File file = new File(uploadPath);
		try {
			file.createNewFile();
			multipartFile.transferTo(file);
		} catch (IllegalStateException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		FileBean f=new FileBean();
		f.setFileName(newFileName);
		f.setFilePath(uploadPath);
		f.setFileRealName(fileRealName);
		f.setSavePath(file.getAbsolutePath());
		return f;
	}
	
	/**
	 * @author dzq
	 * 2016-4-14 下午3:36:15
	 * Description 文件下载 
	 * @param request
	 * @param response
	 * @param fileBean 自定义封装bean （可调用new FileBean(String filePath,String fileRealName)）
	 * @throws IOException 
	 */
	public static void downFile(HttpServletRequest request, HttpServletResponse response,FileBean fileBean) throws IOException{
		response.setContentType("text/html;charset=utf-8");   
        request.setCharacterEncoding("UTF-8");   
        java.io.BufferedInputStream bis = null;   
        java.io.BufferedOutputStream bos = null;
        String downLoadPath = fileBean.getFilePath();
        		//+ fileBean.getFileRealName();
        try {
            File f = new File(downLoadPath);
            if(!f.exists()){
                downLoadPath = request.getSession().getServletContext().getRealPath("")+DEFAULTIMGPATH;
            }
            long fileLength = new File(downLoadPath).length();
            response.setContentType("application/x-msdownload;");   
            response.setHeader("Content-disposition", "attachment; filename="  
                    + (new String(fileBean.getFileRealName().getBytes("utf8"), "ISO8859-1")).replace(" ", ""));
            response.setHeader("Content-Length", String.valueOf(fileLength));   
            bis = new BufferedInputStream(new FileInputStream(downLoadPath));   
            bos = new BufferedOutputStream(response.getOutputStream());   
            byte[] buff = new byte[2048];   
            int bytesRead;   
            while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {   
                bos.write(buff, 0, bytesRead);   
            }   
        } catch (Exception e) {   
            e.printStackTrace();   
        } finally {   
            if (bis != null)   
                bis.close();   
            if (bos != null)   
                bos.close();   
        }
	}

	private static List<String> fileTypes = new ArrayList<String>();
    static {
        fileTypes.add(".jpg");
        fileTypes.add(".jpeg");
        fileTypes.add(".bmp");
        fileTypes.add(".gif");
        fileTypes.add(".png");
    }
	
	/**
	 * @author xiul
	 * 2017-4-7 下午5:56:07
	 * Description Ckeditor文件上传功能，回调，传回图片路径，实现预览效果。
	 * @param request
	 * @param response
	 */
	public static FileBean uploadCkeditorImages(HttpServletRequest request) {
		FileBean fileBean = new FileBean();
		try {
			// 创建一个通用的多部分解析器
			CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());
			// 图片名称
			String fileName = null;
			// 判断 request 是否有文件上传,即多部分请求
			if (multipartResolver.isMultipart(request)) {
				// 转换成多部分request
				MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
				// 取得request中的所有文件名
				Iterator<String> iter = multiRequest.getFileNames();
				while (iter.hasNext()) {
					// 记录上传过程起始时的时间，用来计算上传时间
					// int pre = (int) System.currentTimeMillis();
					// 取得上传文件
					MultipartFile file = multiRequest.getFile(iter.next());
					if (file != null) {
						// 取得当前上传文件的文件名称
						String myFileName = file.getOriginalFilename();
						// 如果名称不为“”,说明该文件存在，否则说明该文件不存在
						if (myFileName.trim() != "") {
							// 获得图片的原始名称
							String originalFilename = file.getOriginalFilename();
							// 获得图片后缀名称,如果后缀不为图片格式，则不上传
							String suffix = originalFilename.substring(originalFilename.lastIndexOf(".")).toLowerCase();
							if (!fileTypes.contains(suffix)) {
							    continue;
							}
							/*// 获得上传路径的绝对路径地址(/upload)-->
							String realPath = request.getSession().getServletContext().getRealPath("/" + StaticValue.CkEditor_UPLOAD_PATH);
							// 如果路径不存在，则创建该路径
							File realPathDirectory = new File(realPath);
							if (realPathDirectory == null || !realPathDirectory.exists()) {
							    realPathDirectory.mkdirs();
							}
							// 重命名上传后的文件名 111112323.jpg
							fileName = UUID.randomUUID().toString().replace("-", "") + suffix;
							// 定义上传路径 .../upload/111112323.jpg
							File uploadFile = new File(realPathDirectory.getAbsolutePath() + "\\" + fileName);
							file.transferTo(uploadFile);*/
							/**
							 * 1、解掉下边的注释
							 * 2、把项目下 ckfileUpload 文件夹下的文件复制到 StaticValue.UPLOAD_PATH 下
							 * 3、运行SQL：
							 */
							// 获得上传路径的绝对路径地址-->
                            String realPath = StaticValue.UPLOAD_PATH;
                            File realPathDirectory = new File(realPath);
                            if (realPathDirectory == null || !realPathDirectory.exists()) {
                                realPathDirectory.mkdirs();
                            }
                            fileName = UUID.randomUUID().toString().replace("-", "") + suffix;
                            String uploadPath = realPath + fileName;
                            File f = new File(uploadPath);
                            f.createNewFile();
                            file.transferTo(f);
                            fileBean.setSavePath(f.getAbsolutePath());
                            fileBean.setFileName(fileName);
                            fileBean.setFileRealName(myFileName);
						}
					}
				}
			}
			
		} catch (IllegalStateException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return fileBean;
	}
	
}
